﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.Entity;
using System.Web.Mvc;
using BulletinModel;
using BulletinMvc.Lib;
using BulletinMvc.Models;
using System.IO;
using Webdiyer.WebControls.Mvc;


namespace BulletinMvc.Controllers
{
    public class BulletinItemController : Controller
    {
        private BulletinDBEntities db;
        private IBulletinItemBL ibl;
        private IFeedbackBL iblfeedback;
        private IBulletinBL iblbulletin;
        public BulletinItemController()
        {
            db=new BulletinDBEntities();
            ibl=new BulletinItemBL(this.ModelState);
            iblfeedback = new FeedbackBL(this.ModelState);
            iblbulletin = new BulletinBL(this.ModelState);
        }

        public ActionResult Details(int BulletinID,int BulletinYaMa ,int pagesize =10, int id = 1)
        {
            ViewData["BulletinID"] = BulletinID;
            ViewData["BulletinYaMa"] = BulletinYaMa;
            ViewData["YeMa"] = id;
            ViewData["BulletinName"] = iblbulletin.GetBulletinName(BulletinID);
            ViewData["BulletinDescription"] = iblbulletin.GetBulletinDescription(BulletinID);
           // bool  BulletinVisible = (from a in db.Bulletins where a.ID == BulletinID select a.Visible).SingleOrDefault();
            //if (BulletinVisible)
            //{
                PagedList<BulletinItem> BulletinItemList = ibl.GetBulletinItemList(BulletinID).ToPagedList(id, pagesize);
                //BulletinItemViewModel model = new BulletinItemViewModel();
                //model.BulletinItemList = ibl.GetBulletinItemList(BulletinID);
                return View(BulletinItemList);

            //}
            //else
            //{

            //    return RedirectToAction("Kongbaiye");
            
            //}

   
        }
        //public ActionResult Kongbaiye() {
        [Authorize]
        public ActionResult CreateBulletinItem(int BulletinID, int BulletinYaMa)
        {
            ViewData["BulletinID"] = BulletinID;
            ViewData["BulletinYaMa"] = BulletinYaMa;
             
            return View();
        }


        [HttpPost]
        public ActionResult CreateBulletinItem(BulletinItemCreateModel BulletinItem, int BulletinID, int BulletinYaMa)
        {
            if (ModelState.IsValid) 
            {
                ViewData["BulletinID"] = BulletinID;
                ViewData["BulletinYaMa"] = BulletinYaMa;
                if (ibl.ExitProjectSN(BulletinItem.ProjectSN.Trim()))
                {
                    ModelState.AddModelError("", "该课题编号已经存在，添加失败！");
                    return View();
                }
                else
                {

                    ibl.AddBulletinItem(BulletinItem, BulletinID);
                    return RedirectToAction("Details", new { BulletinID = BulletinID, BulletinYaMa = BulletinYaMa });            
                }
            
            
            
            }

            return View();        
        }
       
        //}
               [Authorize]
         [HttpPost, ActionName("Details")]
        public ActionResult AddBulletinItem(HttpPostedFileBase fileData, int BulletinID, int BulletinYaMa)
        {
            ViewData["BulletinID"] = BulletinID;
            if (fileData != null)
            {

                try
                {
                    // 文件上传后的保存路径
              //      int SaveBulletinID = Convert.ToInt32(BulletinID);
                    string Bulletinname = (from n in db.Bulletins where n.ID == BulletinID select n.Name).SingleOrDefault();
                    string PathSavename =BulletinID.ToString()+ Bulletinname;
                    string filePath = Server.MapPath("~/Uploads/" + PathSavename );
                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }
                    string fileName = Path.GetFileName(fileData.FileName);// 原始文件名称
                    string fileExtension = Path.GetExtension(fileName); // 文件扩展名
                    if (fileExtension != ".xls" && fileExtension != ".xlsx")
                    {
                        ModelState.AddModelError("", "请excel文件！");
                        return View(ibl.GetDetailsViewList(BulletinID));
                    }
                    string saveName = fileName;// 保存文件名称
                    //  if()
                    var path = Path.Combine(filePath, saveName);

                    //if (System.IO.File.Exists(path))
                    //{
                    //    var script = String.Format("<script>alert('该文件已经添加!');location.href='{0}'</script>", Url.Action("Details", "BulletinItem", new { BulletinID = BulletinID }));
                    //    return Content(script, "text/html");   
                    //    //ModelState.AddModelError("", "该文件已经上传!");
                    //    //return View();
                    ////    System.IO.File.Delete(Server.MapPath(path));
                    //}

                    fileData.SaveAs(path);
                    //添加到数据库
                    if (ibl.saveExcelBulletinItems(filePath, saveName, BulletinID))
                        return RedirectToAction("Details", new { BulletinID = BulletinID, BulletinYaMa=BulletinYaMa });
                    else {
                        return View(ibl.GetDetailsViewList(BulletinID));                
                    }
                }
                catch
                {
                    ModelState.AddModelError("", "导入出错！");                   
                    return View(ibl.GetDetailsViewList(BulletinID));
                  //  return Json(new { Success = false, Message = ex.Message }, JsonRequestBehavior.AllowGet);
                }
            }
            else
            {
                ModelState.AddModelError("", "请excel文件！");
                return View(ibl.GetDetailsViewList(BulletinID));

                //var script = String.Format("<script>alert('选择Excel文件!');location.href='{0}'</script>", Url.Action("Details", "BulletinItem", new { BulletinID = BulletinID }));
                //return Content(script, "text/html");   

             //   return Json(new { Success = false, Message = "请选择要上传的文件！" }, JsonRequestBehavior.AllowGet);
            }

         //   return View();
        }
     //   [HttpPost,HttpGet]
         public ActionResult giveComment(string ProjectSN, int YeMa, int BulletinYaMa)
        {
             ViewData["YeMa"]=YeMa;
             ViewData["BulletinYaMa"] = BulletinYaMa;
             
            if (Request.RequestType == "POST")
            {
                ViewData["ProjectSN"] = urlencode.UrlEncrypt( ProjectSN);
                var projectitem = db.BulletinItems.Single(a => a.ProjectSN == ProjectSN);
                return View(projectitem);
            }
            else {
                //ViewData["ProjectSN"] =ProjectSN;
                //string DecryptProjectSN=urlencode.UrlDecrypt(ProjectSN);            
                var projectitem = db.BulletinItems.Single(a => a.ProjectSN==ProjectSN);
                return View(projectitem);        
            }
        //    return View();
        }


       //public ActionResult CommentStatistics(int id)
       //{
       //    return View();
       //}


        //
        // GET: /BulletinItem/Edit/5

        //public ActionResult Edit(string ProjectSN)
        //{
        //    return View();
        //}

        //
        // POST: /BulletinItem/Edit/5

       // [HttpPost]
               [Authorize]
        public ActionResult Edit(string ProjectSN, int BulletinID, int BulletinYaMa, int YeMa )
        {
            ViewData["BulletinYaMa"] = BulletinYaMa;
            ViewData["YeMa"] =YeMa;
            ViewData["BulletinID"] = BulletinID;
         //   string deProjectSN = urlencode.UrlDecrypt(ProjectSN);
            return View(ibl.GetBulletinItemDetail(ProjectSN));

        }
        [HttpPost]
        public ActionResult Editcomfirm(BulletinItemCreateModel BulletinItem, int BulletinID, int BulletinYaMa, int YeMa)
        {
            if (ModelState.IsValid)
            {
                ibl.saveBulletinItem(BulletinItem,BulletinID);
                return RedirectToAction("giveComment", new { ProjectSN = BulletinItem.ProjectSN, YeMa = YeMa, BulletinYaMa = BulletinYaMa });     
            }
            else 
            {
                ModelState.AddModelError("", "修改出错！");
                return View(ibl.GetBulletinItemDetail(BulletinItem.ProjectSN));          
            }

        //    return View();

        }
        //
        // GET: /BulletinItem/Delete/5
               [Authorize]
        public ActionResult Delete(string ProjectSN, int BulletinID, int BulletinYaMa,int YeMa )
        {
            ViewData["ProjectSN"] = ProjectSN;
            ViewData["BulletinID"] = BulletinID;
            ViewData["BulletinYaMa"] = BulletinYaMa;
            ViewData["YeMa"] = YeMa;
            return View(ibl.GetBulletinItemDetail(ProjectSN));

         //   return View();
        }

        //
        // POST: /BulletinItem/Delete/5

        [HttpPost]
        public ActionResult DeleteComfirm(string ProjectSN, int BulletinID, int BulletinYaMa, int YeMa)
        {
            try
            {
                // TODO: Add delete logic here

                if (iblfeedback.HaveCommentByprojectSN(ProjectSN)) 
                {

                    //var script = String.Format("<script>alert('该项目已经有评论存在, 不能删除！!');location.href='{0}'</script>", Url.Action("giveComment", "BulletinItem", new { ProjectSN = urlencode.UrlEncrypt(ProjectSN) }));
                    //return Content(script, "text/html");   
                    ModelState.AddModelError("", "该项目已经有评论存在, 不能删除！");
                    return View("Delete", ibl.GetBulletinItemDetail(ProjectSN));
                }
                else if (ibl.DeleteBulletinItem(ProjectSN))
                {

                    int aa = ibl.GetBulletinItemCount(BulletinID) / 1;
                    if (aa < YeMa)
                        return RedirectToAction("Details", new { BulletinID = BulletinID, BulletinYaMa = BulletinYaMa, id = ibl.GetBulletinItemCount(BulletinID) / 1 });
                    else
                        return RedirectToAction("Details", new { BulletinID = BulletinID, BulletinYaMa = BulletinYaMa, id = YeMa });

                }
                else {
                    ModelState.AddModelError("", "删除出错!");
                    return View("Delete", ibl.GetBulletinItemDetail(ProjectSN));               
                
                }
                
            }
            catch
            {
                ModelState.AddModelError("", "删除出错!");
                return View("Delete", ibl.GetBulletinItemDetail(ProjectSN));

            }
        }
    }
}
